package com.atguigu.spzx.common.config;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
public class SpzxRedisConfig {
    @Resource
    RedisTemplate redisTemplate;
    //jdk原生注解：可以在当前类构造器执行后执行该注解标注的方法
    @PostConstruct
    public void init(){
        //所有的键直接转为普通字符串存入
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //使用Jackson 可以将存入的对象自动转为json字符窜、将读取的字符串转为对象
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        //配置hash结构的键值序列化器
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
    }

    //cacheManager方法内需要使用连接工厂，引入的commons-pool2提供了实现，项目启动时会注入到容器中
    @Bean
    public CacheManager cacheManager(LettuceConnectionFactory connectionFactory){
        // 缓存穿透、雪崩、击穿
        return RedisCacheManager
                //构建redis缓存管理器：需要传入redis的连接工厂
                .builder(connectionFactory)
                //添加缓存管理的配置： 键值序列化器、缓存的时间、是否缓存空值
                .cacheDefaults(RedisCacheConfiguration
                        .defaultCacheConfig()
                        .entryTtl(Duration.ofSeconds(600)) //缓存的过期时间
                        .serializeKeysWith(RedisSerializationContext.SerializationPair
                                .fromSerializer(new StringRedisSerializer())) //键的序列化器
                        .serializeValuesWith(RedisSerializationContext.SerializationPair
                                .fromSerializer(new GenericJackson2JsonRedisSerializer())) //值的序列化器
//                        .disableCachingNullValues() //禁用缓存空值
                )
                .build();
    }

}
